import { showLoading } from '$components/basic/message';
import { persistentWritable } from '$utils/persist';
import { alova } from '$utils/request';
import { get } from 'svelte/store';

export type CountryItem = {
	id: number;
	name: string;
	continent_id: number;
};

export const useCountryStore = () => {
	const countries = persistentWritable<CountryItem[]>('countries', []);

	const getCountries = async () => {
		if (!get(countries).length) {
			const msg = showLoading();
			const res = (await alova
				.Post('/world/get-country-list', { pCountry: 0 })
				.catch(msg.error)) as IObject;
			countries.set(res.data as CountryItem[]);
			msg.close();
		}

		return get(countries);
	};

	return { getCountries };
};
